package com.siterwell.awsiotapp;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.internal.TextWatcherAdapter;
import com.guard.aws.AwsMQTTCallBackObserver;
import com.guard.aws.AwsMQTTConnectObserver;
import com.guard.aws.AwsMQTTProxy;
import com.guard.aws.AwsMQTTPushCallback;

public class MainActivity extends AppCompatActivity implements AwsMQTTCallBackObserver {

    private TextView mMessage;

    private Button mPublish;

    private String mInputString;

    private Handler mHandler;

    private final String endpoint = "a22kpq659tmps7-ats.iot.us-west-2.amazonaws.com";

    private String poolId = "us-west-2:11f3d596-ede2-4673-b59c-618c10faaa50";

    private String topic = "FamilyLink";

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AwsMQTTProxy.getInstance().initMQTT(this, endpoint, poolId, topic);
        AwsMQTTConnectObserver.getInstance().registerObserver(this);

        mMessage = findViewById(R.id.tv_message);
        mPublish = findViewById(R.id.bt_publish);

        EditText editText = findViewById(R.id.et_message);
        editText.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(@NonNull Editable editable) {
                mInputString = editable.toString();
            }
        });
        mHandler = new Handler(Looper.getMainLooper());

        mPublish.setOnClickListener(view -> {
            String message = "{\n" +
                    "  \"message\": \"" + mInputString + "\"" +
                    "\n}";
            AwsMQTTProxy.getInstance().pushMQTTString("FamilyWell", message, result -> {
                String log = result ? "发送成功" : "发送失败";
                Log.i("AAA", "onCreate: " + log);
            });
        });
    }

    @Override
    public void onMQTTReceive(String message) {
        mHandler.post(()-> mMessage.setText(message));
    }

    @Override
    public void onMQTTDisconnected() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AwsMQTTConnectObserver.getInstance().unRegisterObserver(this);
    }
}